<?php

namespace App\Jobs\Publish;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Entity\Pm\PriceController;
use App\Models\Entity\Pm\Price;
use App\Models\Task\Task;
use App\Models\Entity\Pm\PriceVasseti;
use App\Classes\Publish\Publication;

class PriceJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $ids;
    protected $option;
    public $tries   = 1;
    public $timeout = 30;
    public $taskid;
    // 上线,下线,发布的where条件
    protected $upWhere          = ['online_status' => 0, 'publish_down_status' => 1];
    protected $publishWhere     = ['online_status' => 1, 'publish_status'      => 0];
    protected $downWhere        = ['online_status' => 1];
    protected $publishDownWhere = ['online_status' => 0, 'publish_down_status' => 0];
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($option, $ids = '', $taskid = '')
    {
        $this->option = $option;
        $this->ids    = $ids;
        $this->taskid = $taskid;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        switch ($this->option[0]) {
            // 分发任务,将一个大任务划分为多个小任务
            case 'dispatch':
                $this->mydispatch($this->option[1]);
                break;
            // 上线小任务
            case 'up':
                $user_id = Publication::getField(new Task(), $this->taskid, 'user_id');
                // 获取有媒资的单点定价和有产品包的定价的ids
                $hasVassetiIds = PriceVasseti::whereIn('price_id', $this->ids)->pluck('price_id')->unique();
                $hasPmtagIds = Price::whereIn('id', $this->ids)->where(['type' => 1])->whereNotNull('pmtag_id')->pluck('id');
                $total_num = $hasVassetiIds->count() + $hasPmtagIds->count();
                $ids = $hasVassetiIds->merge($hasPmtagIds);
                Publication::updateMany(new Price(), $ids, [
                    'online_status'       => 1, 
                    'publish_down_status' => 0, 
                    'user_id'             => $user_id, 
                    'online_at'           => date('Y-m-d H:i:s')
                ]);
                Publication::updateOne(new Task(), $this->taskid, ['done_num' => DB::raw('done_num +' . $total_num)]);
                break;
            // 发布小任务
            case 'publish':
                $publish_small_chunk_num = config('custom.base.job.price.publish_small_chunk_num');
                foreach ($this->ids->chunk($publish_small_chunk_num) as $chunk_ids) {
                    try {
                        $prices         = Price::whereIn('id',$chunk_ids)->get();
                        $total_num = $prices->count();
                        PriceVasseti::whereIn('price_id', $chunk_ids)->chunk($publish_small_chunk_num, function($price_vassetis) use (&$total_num){
                            $price_vasseti_datas = self::makePriceVassetis($price_vassetis);
                            DB::connection('interface')->table('price_vassetis')->insert($price_vasseti_datas);
                        });
                    } catch(\Exception $e) {
                        dd($e->getMessage());
                    }
                    // 拼装产品包数据, 产品包-媒资中间表数据
                    $price_datas = self::makePrices($prices);
                    DB::connection('interface')->beginTransaction();
                    try {
                        DB::connection('interface')->table('prices')->insert($price_datas);
                        DB::connection('interface')->commit();
                        Publication::updateMany(new Price(), $chunk_ids, ['publish_status' => 1]);
                        Publication::updateOne(new Task(), $this->taskid, [
                            'done_num' => DB::raw('done_num + ' . $total_num)
                        ]);
                    } catch (\Exception $e) {
                        DB::connection('interface')->rollback(); //事务回滚
                        dd($e->getMessage());
                    }
                }
                break;
            // 下线小任务
            case 'down':
                $user_id = Publication::getField(new Task(), $this->taskid, 'user_id');
                Publication::updateMany(new Price(), $this->ids, [
                    'online_status'  => 0, 
                    'publish_status' => 0, 
                    'user_id'        => $user_id, 
                    'offline_at'     => date('Y-m-d H:i:s')
                ]);
                Publication::updateOne(new Task(), $this->taskid, ['done_num' => DB::raw('done_num +' . count($this->ids))]);
                break;
            // 下线发布小任务
            case 'publishDown':
                $user_id = Publication::getField(new Task(), $this->taskid, 'user_id');
                Publication::deleteApi('prices', 'price_id', $this->ids);
                Publication::deleteApi('price_vassetis', 'price_id', $this->ids);
                $done_num = Publication::getTotal(new PriceVasseti(), 'price_id', $this->ids);
                Publication::updateMany(new Price(), $this->ids, [
                     'publish_down_status' => 1, 
                     'user_id'             => $user_id, 
                ]);
                Publication::updateOne(new Task(), $this->taskid, ['done_num' => DB::raw('done_num +' . count($this->ids))]);
                break;
        }
    }
    
    /**
    * 分发任务具体执行代码
    */
    public function mydispatch($option)
    {
        switch ($option) {
            case 'up':
                $chunk_num = config('custom.base.job.price.online_chunk_num');
                $where = $this->upWhere;
                break;
            case 'publish':
                $chunk_num = config('custom.base.job.price.publish_chunk_num');
                $where = $this->publishWhere;
                break;
            case 'down':
                $chunk_num = config('custom.base.job.price.offline_chunk_num');
                $where = $this->downWhere;
                break;
            case 'publishDown':
                $chunk_num = config('custom.base.job.price.publish_chunk_num');
                $where = $this->publishDownWhere;
                break;
        }
        Publication::chunk(new Price(), $this, $where, $chunk_num, [$option]);
    }

    /**
    * 拼装定价数据
    */
    public static function makePrices($prices)
    {
        $data  = [];
        $datas = [];
        foreach ($prices as $price) {
            $data['price_id']           = $price->id;
            $data['name']               = $price->name;
            $data['title']              = $price->title;
            $data['subtitle']           = $price->subtitle;
            $data['short_desc']         = $price->short_desc;
            $data['prices']             = $price->prices;
            $data['pmtag_id']           = $price->pmtag_id;
            $data['metering_period_id'] = $price->metering_period_id;
            $data['startdate']          = $price->startdate;
            $data['enddate']            = $price->enddate;
            $data['type']               = $price->type;
            $data['status']             = $price->status;
            $data['expiry_date_id']     = $price->expiry_date_id;
            $data['sdk_price_id']       = $price->sdk_price_id;
            $data['listorder']          = $price->listorder;
            $datas[]                    = $data;
        }
        return $datas;
    }

    /**
    * 拼装定价数据
    */
    public static function makePriceVassetis($price_vassetis)
    {
        $data  = [];
        $datas = [];
        foreach ($price_vassetis as $price_vasseti) {
             $data['price_id']   = $price_vasseti->price_id;
             $data['vasseti_id'] = $price_vasseti->vasseti_id;
             $datas[]            = $data;
        }
        return $datas;
    }

}
